<template>
  <div class="card-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>银行卡管理</h1>
      <p>管理您的银行卡，可进行挂失、查看详情等操作</p>
    </div>

    <!-- 功能说明卡片 -->
    <el-card class="info-card" shadow="hover">
      <div class="info-content">
        <div class="info-title">
          <el-icon><InfoFilled /></el-icon>
          <span>银行卡挂失说明</span>
        </div>
        <div class="info-text">
          <p>• 银行卡挂失后将立即冻结账户，无法进行任何交易</p>
          <p>• 挂失后可前往柜台或通过客服申请补办新卡</p>
          <p>• 如不慎挂失，可在24小时内申请解挂（部分卡种支持）</p>
        </div>
      </div>
    </el-card>

    <!-- 银行卡列表 -->
    <el-card class="card-list-card" shadow="hover">
      <div class="card-header">
        <div class="card-title">我的银行卡</div>
        <el-button type="primary" @click="openAddCardDialog">
          <el-icon><Plus /></el-icon>添加银行卡
        </el-button>
      </div>

      <div v-if="cards.length === 0" class="empty-list">
        <el-icon class="empty-icon"><CreditCard /></el-icon>
        <p>您还没有添加银行卡</p>
        <el-button type="primary" @click="openAddCardDialog"
          >添加银行卡</el-button
        >
      </div>

      <el-table v-else :data="cards" stripe style="width: 100%">
        <el-table-column prop="cardID" label="卡号" width="240" />
        <el-table-column prop="curID" label="卡类型" width="120" />
        <el-table-column prop="balance" label="余额" width="120">
          <template #default="{ row }">
            <span v-if="!row.isLost">¥{{ row.balance }}</span>
            <span v-else class="lost-balance">已挂失</span>
          </template>
        </el-table-column>
        <el-table-column prop="openDate" label="开卡日期" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isLost ? 'danger' : 'success'">
              {{ row.isLost ? "已挂失" : "正常" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button
              v-if="!row.isLost"
              type="danger"
              size="small"
              @click="reportLoss(row.cardID)"
            >
              <el-icon><Lock /></el-icon>挂失
            </el-button>
            <el-button
              v-if="row.isLost"
              type="primary"
              size="small"
              @click="dereportLoss(row.cardID)"
            >
              <el-icon><Unlock /></el-icon>解挂
            </el-button>
            <el-button type="info" size="small" @click="viewCardDetails(row)">
              <el-icon><InfoFilled /></el-icon>详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 卡片详情 -->
    <el-card class="card-detail-card" shadow="hover" v-if="currentCard">
      <div class="detail-header">
        <h3>卡片详情</h3>
      </div>
      <div class="detail-content">
        <div class="detail-item">
          <span class="detail-label">卡号：</span>
          <span class="detail-value">{{ currentCard.cardID }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">卡类型：</span>
          <span class="detail-value">{{ currentCard.curID }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">余额：</span>
          <span class="detail-value">¥{{ currentCard.balance }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">开卡日期：</span>
          <span class="detail-value">{{ currentCard.openDate }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">状态：</span>
          <span class="detail-value">{{
            currentCard.isLost ? "已挂失" : "正常"
          }}</span>
        </div>
      </div>
    </el-card>

    <!-- 添加银行卡对话框 -->
    <el-dialog
      v-model="addCardDialogVisible"
      title="添加银行卡"
      width="30%"
      center
    >
      <el-form
        :model="newCard"
        ref="addCardFormRef"
        label-width="80px"
        :rules="cardRules"
      >
        <el-form-item label="卡号" prop="cardID">
          <el-input v-model="newCard.cardID"></el-input>
        </el-form-item>
        <el-form-item label="卡类型" prop="curID">
          <el-input v-model="newCard.curID"></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input-number v-model="newCard.balance" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newCard.username"></el-input>
        </el-form-item>
        <el-form-item label="储蓄ID" prop="savingID">
          <el-input-number
            v-model="newCard.savingID"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input v-model="newCard.pass" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addCardDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddCardForm"
            >确认添加</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 操作成功提示 -->
    <el-message
      v-model="successMessageVisible"
      type="success"
      :message="successMessage"
      center
      :duration="3000"
    />
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import {
  InfoFilled,
  Plus,
  CreditCard,
  Lock,
  Unlock,
} from "@element-plus/icons-vue";

export default {
  name: "CardManagementView",
  components: {
    InfoFilled,
    Plus,
    CreditCard,
    Lock,
    Unlock,
  },
  setup() {
    // 银行卡数据
    const cards = ref([]);
    const successMessageVisible = ref(false);
    const successMessage = ref("");
    const addCardDialogVisible = ref(false);
    const currentCard = ref(null);
    const username = ref("");
    const newCard = ref({
      cardID: "",
      curID: "",
      username: "",
      savingID: null,
      balance: 0,
      pass: "",
    });
    const addCardFormRef = ref(null);

    // 表单验证规则
    // const cardRules = {
    //   cardID: [{ required: true, message: "请输入卡号", trigger: "blur" }],
    //   curID: [{ required: true, message: "请输入卡类型", trigger: "blur" }],
    //   balance: [{ required: true, message: "请输入余额", trigger: "blur" }],
    //   username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    //   savingID: [{ required: true, message: "请输入储蓄ID", trigger: "blur" }],
    //   pass: [{ required: true, message: "请输入密码", trigger: "blur" }],
    // };

    // 从 localStorage 获取用户名
    onMounted(() => {
      username.value = localStorage.getItem("username");
      if (!username.value) {
        ElMessage.error("获取用户名失败，请重新登录");
        return;
      }
      fetchCards();
    });

    // 获取银行卡信息
    const fetchCards = async () => {
      try {
        if (!username.value) {
          ElMessage.error("获取用户名失败，请重新登录");
          return;
        }
        const response = await axios.get(
          `http://localhost:8088/api/cards/user?username=${username.value}`
        );

        cards.value = response.data.map((card) => {
          const openDate = new Date(card.openDate);
          const isLost = card.isReportLoss === "是";

          return {
            id: card.cardID,
            cardID: card.cardID,
            curID: card.curID,
            balance: card.balance,
            openDate: openDate,
            isLost: isLost,
          };
        });
        // 默认选择第一张卡
        if (cards.value.length > 0) {
          currentCard.value = cards.value[0];
        }
      } catch (error) {
        console.error("获取银行卡数据失败:", error);
        ElMessage.error("获取银行卡数据失败，请检查网络连接");
      }
    };

    // 挂失银行卡
    const reportLoss = (cardID) => {
      axios
        .put(`http://localhost:8088/api/cards/reportloss/${cardID}`)
        .then((response) => {
          if (response.data === "挂失成功") {
            const cardIndex = cards.value.findIndex((c) => c.cardID === cardID);
            if (cardIndex !== -1) {
              cards.value[cardIndex].isLost = true;
              showSuccessMessage(`银行卡 ${cardID} 挂失成功`);
            }
          } else {
            ElMessage.error("挂失失败");
          }
        })
        .catch((error) => {
          console.error("挂失失败:", error);
          ElMessage.error("挂失失败，请检查网络连接");
        });
    };

    // 解挂银行卡
    const dereportLoss = (cardID) => {
      axios
        .put(`http://localhost:8088/api/cards/dereportloss/${cardID}`)
        .then((response) => {
          if (response.data === "解挂成功") {
            const cardIndex = cards.value.findIndex((c) => c.cardID === cardID);
            if (cardIndex !== -1) {
              cards.value[cardIndex].isLost = false;
              showSuccessMessage(`银行卡 ${cardID} 解挂成功`);
            }
          } else {
            ElMessage.error("解挂失败");
          }
        })
        .catch((error) => {
          console.error("解挂失败:", error);
          ElMessage.error("解挂失败，请检查网络连接");
        });
    };

    // 查看银行卡详情
    const viewCardDetails = (card) => {
      currentCard.value = card;
    };

    // 打开添加银行卡对话框
    const openAddCardDialog = () => {
      addCardDialogVisible.value = true;
    };

    // 提交添加银行卡表单
    const submitAddCardForm = () => {
      addCardFormRef.value.validate((valid) => {
        if (valid) {
          axios
            .post("http://localhost:8088/api/cards/insert", newCard.value)
            .then((response) => {
              if (response.data > 0) {
                // 添加成功后刷新银行卡列表
                fetchCards();
                addCardDialogVisible.value = false;
                showSuccessMessage("银行卡添加成功");
                newCard.value = {
                  cardID: "",
                  curID: "",
                  username: "",
                  savingID: null,
                  balance: 0,
                  pass: "",
                };
              } else {
                ElMessage.error("添加银行卡失败");
              }
            })
            .catch((error) => {
              console.error("添加银行卡失败:", error);
              ElMessage.error("添加银行卡失败，请检查网络连接");
            });
        }
      });
    };

    // 显示成功提示
    const showSuccessMessage = (message) => {
      successMessage.value = message;
      successMessageVisible.value = true;
    };

    return {
      cards,
      successMessageVisible,
      successMessage,
      openAddCardDialog,
      addCardDialogVisible,
      newCard,
      addCardFormRef,
      submitAddCardForm,
      showSuccessMessage,
      currentCard,
      viewCardDetails,
      reportLoss,
      dereportLoss,
    };
  },
};
</script>

<style scoped>
.card-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
}

.info-card {
  background-color: #e6f7ff;
  border-radius: 12px;
  margin-bottom: 20px;
}

.info-content {
  padding: 20px;
}

.info-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #1890ff;
}

.info-title i {
  margin-right: 8px;
}

.info-text {
  line-height: 1.8;
  color: #333;
  font-size: 14px;
}

.card-list-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
}

.empty-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.empty-icon {
  font-size: 60px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.lost-balance {
  color: #909399;
  font-style: italic;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header h1 {
    font-size: 24px;
  }

  .card-list-card {
    margin-top: 10px;
  }
}

/* 新增样式 */
.card-detail-card {
  margin-top: 20px;
}

.detail-header {
  margin-bottom: 15px;
}

.detail-content {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.detail-item {
  margin-bottom: 10px;
  display: flex;
}

.detail-label {
  width: 100px;
  font-weight: bold;
}

.detail-value {
  flex: 1;
}
</style>
